import { NextResponse } from 'next/server'
import { db } from '@/lib/db'

// 4级状态体系定义
const PROJECT_STATES = [
  // 一级状态：项目主状态
  { name: 'DRAFT', level: 1, description: '草稿', color: '#6B7280', order: 1 },
  { name: 'REVIEW', level: 1, description: '审核中', color: '#F59E0B', order: 2 },
  { name: 'APPROVED', level: 1, description: '已批准', color: '#3B82F6', order: 3 },
  { name: 'RELEASED', level: 1, description: '已发布', color: '#10B981', order: 4 },
  { name: 'ARCHIVED', level: 1, description: '已归档', color: '#EF4444', order: 5 },
  
  // 二级状态：子状态
  { name: '草稿阶段', level: 2, description: '项目草稿阶段', color: '#9CA3AF', order: 1 },
  { name: '董事长审批', level: 2, description: '董事长审批中', color: '#FCD34D', order: 2 },
  { name: '经理审批', level: 2, description: '经理审批中', color: '#FDE68A', order: 3 },
  { name: '规划阶段', level: 2, description: '项目规划阶段', color: '#93C5FD', order: 4 },
  { name: '执行阶段', level: 2, description: '项目执行阶段', color: '#86EFAC', order: 5 },
  { name: '验收阶段', level: 2, description: '项目验收阶段', color: '#6EE7B7', order: 6 },
  { name: '维护阶段', level: 2, description: '项目维护阶段', color: '#FCA5A5', order: 7 },
  
  // 三级状态：活动状态
  { name: '需求分析', level: 3, description: '需求分析阶段', color: '#D1D5DB', order: 1 },
  { name: '方案设计', level: 3, description: '方案设计阶段', color: '#FEF3C7', order: 2 },
  { name: '原理图设计', level: 3, description: '原理图设计阶段', color: '#FED7AA', order: 3 },
  { name: 'PCB设计', level: 3, description: 'PCB设计阶段', color: '#DBEAFE', order: 4 },
  { name: '固件开发', level: 3, description: '固件开发阶段', color: '#BFDBFE', order: 5 },
  { name: '软件开发', level: 3, description: '软件开发阶段', color: '#BBF7D0', order: 6 },
  { name: '硬件调试', level: 3, description: '硬件调试阶段', color: '#A7F3D0', order: 7 },
  { name: '系统集成', level: 3, description: '系统集成阶段', color: '#FECACA', order: 8 },
  { name: '测试验证', level: 3, description: '测试验证阶段', color: '#FCA5A5', order: 9 },
  
  // 四级状态：活动子状态
  { name: '初步设计', level: 4, description: '初步设计阶段', color: '#E5E7EB', order: 1 },
  { name: '详细设计', level: 4, description: '详细设计阶段', color: '#F3F4F6', order: 2 },
  { name: '代码编写', level: 4, description: '代码编写阶段', color: '#EFF6FF', order: 3 },
  { name: '单元测试', level: 4, description: '单元测试阶段', color: '#F0F9FF', order: 4 },
  { name: '集成测试', level: 4, description: '集成测试阶段', color: '#ECFDF5', order: 5 },
  { name: '系统测试', level: 4, description: '系统测试阶段', color: '#F0FDF4', order: 6 }
]

// 状态转换规则
const STATE_TRANSITIONS = [
  // 草稿状态转换
  { fromState: 'DRAFT', toState: 'REVIEW', name: '提交审核', description: '提交项目进行审核' },
  { fromState: 'DRAFT', toState: 'ARCHIVED', name: '直接归档', description: '直接归档项目' },
  
  // 审核状态转换
  { fromState: 'REVIEW', toState: 'APPROVED', name: '审核通过', description: '项目审核通过' },
  { fromState: 'REVIEW', toState: 'DRAFT', name: '退回修改', description: '退回项目进行修改' },
  
  // 批准状态转换
  { fromState: 'APPROVED', toState: 'RELEASED', name: '发布项目', description: '发布项目' },
  { fromState: 'APPROVED', toState: 'REVIEW', name: '重新审核', description: '重新提交审核' },
  
  // 发布状态转换
  { fromState: 'RELEASED', toState: 'ARCHIVED', name: '归档项目', description: '归档已完成的项目' },
  
  // 归档状态转换
  { fromState: 'ARCHIVED', toState: 'DRAFT', name: '重新激活', description: '重新激活归档的项目' }
]

async function initializeProjectStates() {
  try {
    // 创建项目状态
    for (const state of PROJECT_STATES) {
      await db.projectState.upsert({
        where: { name: state.name },
        update: state,
        create: state
      })
    }
    
    // 创建状态转换规则
    for (const transition of STATE_TRANSITIONS) {
      await db.stateTransition.upsert({
        where: { 
          fromState_toState: {
            fromState: transition.fromState,
            toState: transition.toState
          }
        },
        update: transition,
        create: transition
      })
    }
    
    console.log('Project states initialized successfully')
  } catch (error) {
    console.error('Error initializing project states:', error)
  }
}

export async function GET() {
  try {
    // 自动初始化项目状态
    await initializeProjectStates()
    
    const states = await db.projectState.findMany({
      orderBy: [
        { level: 'asc' },
        { order: 'asc' }
      ]
    })
    
    const transitions = await db.stateTransition.findMany({
      include: {
        fromStateRel: true,
        toStateRel: true
      },
      orderBy: [
        { fromState: 'asc' },
        { toState: 'asc' }
      ]
    })
    
    // 按级别组织状态
    const statesByLevel = states.reduce((acc, state) => {
      if (!acc[state.level]) {
        acc[state.level] = []
      }
      acc[state.level].push(state)
      return acc
    }, {} as Record<number, typeof states>)
    
    return NextResponse.json({
      states,
      statesByLevel,
      transitions,
      metadata: {
        totalStates: states.length,
        totalTransitions: transitions.length,
        levels: Object.keys(statesByLevel).map(Number).sort()
      }
    })
  } catch (error) {
    console.error('Error fetching project states:', error)
    return NextResponse.json(
      { error: 'Failed to fetch project states' },
      { status: 500 }
    )
  }
}